package com.wsm.common.aspect;

import com.wsm.common.annotation.CurDataSource;
import com.wsm.common.config.DynamicDataSource;
import com.wsm.common.enums.DataSourceName;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 多数据源，切面处理类
 *
 * @author wangshimin
 */
@Slf4j
@Aspect
@Component
@Order(3)
public class DataSourceAspect {

    @Pointcut("@annotation(com.wsm.common.annotation.CurDataSource)")
    public void dataSourcePointCut() {
    }

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        CurDataSource ds = method.getAnnotation(CurDataSource.class);
        if (ds == null) {
            DynamicDataSource.setDataSource(DataSourceName.First);
            log.debug("切换数据源为{}" + DataSourceName.First.getName());
        } else {
            DynamicDataSource.setDataSource(ds.name());
            log.debug("切换数据源为{} " + ds.name());
        }
        try {
            return point.proceed();
        } finally {
            DynamicDataSource.clearDataSource();
            log.debug("清楚数据库信息");
        }
    }
}
